package cn.lds.healthj377.controller;

import cn.lds.healthj377.domain.User;
import cn.lds.healthj377.dto.ResponseDTO;
import cn.lds.healthj377.exception.SysException;
import cn.lds.healthj377.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(HttpSession session) throws SysException {

        Object loginUser = session.getAttribute("loginUser");

        if (Objects.nonNull(loginUser)){
            throw new SysException(ResponseDTO.buildError("您已登录，请注销后充实"));
        }

        return "login";
    }

    @RequestMapping(value = "do_login",method = RequestMethod.POST)
    public String doLogin(User user, Model model, HttpSession session) throws SysException {
        ResponseDTO<User> userResponseDTO = userService.loginUser(user);

        log.info("log:{}",userResponseDTO);
        if (userResponseDTO.getCode().equals(4000)){
            model.addAttribute("loginErr",userResponseDTO.getMsg());
            //转发到登录页
            return "login";
        }
        session.setAttribute("loginUser",userResponseDTO.getData());
        //重定向会首页
        return "redirect:/";

    }

    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        return "redirect:/";
    }

    @RequestMapping("reg")
    public String reg(){
        return "reg";
    }

    @RequestMapping(value = "do_reg",method = RequestMethod.POST)
    public String doReg(User user) throws SysException {
        userService.regUser(user);

        return "login";
    }
}
